<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="研究方向" prop="departmentName">
        <el-input
          v-model="queryParams.departmentName"
          placeholder="请输入部门/研究方向"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="经办人" prop="applicantName">
        <el-input
          v-model="queryParams.applicantName"
          placeholder="请输入经办人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商" prop="supplier">
        <el-input
          v-model="queryParams.supplier"
          placeholder="请输入供应商"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="验收日期" prop="requiredDate">
        <el-date-picker clearable
          v-model="queryParams.requiredDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择验收日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="本次到货金额合计" prop="deliveryAmount">
        <el-input
          v-model="queryParams.deliveryAmount"
          placeholder="请输入本次到货金额合计"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否存在分批到货" prop="ifBatchDelivery">
         <el-select v-model="queryParams.ifBatchDelivery" placeholder="请选择审批状态" clearable>
                    <el-option
                      v-for="dict in dict.type.yy_bip_tf"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
      </el-form-item>
      <el-form-item label="是否YS合同" prop="ifYsConstruct">
        <el-select v-model="queryParams.ifYsConstruct" placeholder="请选择审批状态" clearable>
                    <el-option
                      v-for="dict in dict.type.yy_bip_tf"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
      </el-form-item>
      <el-form-item label="到货日期" prop="arrivalDate">
        <el-date-picker clearable
          v-model="queryParams.arrivalDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择到货日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="物料名称" prop="materialName">
        <el-input
          v-model="queryParams.materialName"
          placeholder="请输入物料名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="合同数量" prop="contractQuantity">
        <el-input
          v-model="queryParams.contractQuantity"
          placeholder="请输入合同数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="本次实际到货数量" prop="actualDeliveryQuantity">
        <el-input
          v-model="queryParams.actualDeliveryQuantity"
          placeholder="请输入本次实际到货数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="验收结果" prop="acceptanceResult">
        <el-input
          v-model="queryParams.acceptanceResult"
          placeholder="请输入验收结果"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
       <el-form-item label="审批状态" prop="approveStatus">
       <el-select v-model="queryParams.approveStatus" placeholder="请选择审批状态" clearable>
                    <el-option
                      v-for="dict in dict.type.yy_bip_status"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['sci:acceptance:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['sci:acceptance:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['sci:acceptance:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['sci:acceptance:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="acceptanceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
     
      <el-table-column label="部门/研究方向" align="center" prop="departmentName" />
      <el-table-column label="经办人" align="center" prop="applicantName" />
      <el-table-column label="供应商" align="center" prop="supplier" />
      <el-table-column label="验收日期" align="center" prop="requiredDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.requiredDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="本次到货金额合计" align="center" prop="deliveryAmount" />
      <el-table-column label="是否存在分批到货" align="center" prop="ifBatchDelivery" >
          <template slot-scope="scope">
            <dict-tag :options="dict.type.yy_bip_tf" :value="scope.row.ifBatchDelivery"/>
          </template>
      </el-table-column>
      
      <el-table-column label="是否YS合同" align="center" prop="ifYsConstruct" >
        <template slot-scope="scope">
            <dict-tag :options="dict.type.yy_bip_tf" :value="scope.row.ifYsConstruct"/>
          </template>
      </el-table-column>
      <el-table-column label="到货日期" align="center" prop="arrivalDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.arrivalDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="物料名称" align="center" prop="materialName" />
      <el-table-column label="合同数量" align="center" prop="contractQuantity" />
      <el-table-column label="本次实际到货数量" align="center" prop="actualDeliveryQuantity" />
      <el-table-column label="验收结果" align="center" prop="acceptanceResult" />
         <el-table-column label="审批状态" align="center" prop="approveStatus" >
         <template slot-scope="scope">
            <dict-tag :options="dict.type.yy_bip_status" :value="scope.row.approveStatus"/>
          </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['sci:acceptance:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['sci:acceptance:remove']"
          >删除</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleView(scope.row)"
            v-hasPermi="['sci:acceptance:query']"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备（货物验收数据）对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="单据编号" prop="documentNumber">
          <el-input v-model="form.documentNumber" placeholder="请输入单据编号" />
        </el-form-item>
        <el-form-item label="单据日期" prop="documentDate">
          <el-date-picker clearable
            v-model="form.documentDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择单据日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="采购单位" prop="applicantOrgName">
          <el-input v-model="form.applicantOrgName" placeholder="请输入采购单位" />
        </el-form-item>
        <el-form-item label="部门/研究方向" prop="departmentName">
          <el-input v-model="form.departmentName" placeholder="请输入部门/研究方向" />
        </el-form-item>
        <el-form-item label="经办人" prop="applicantName">
          <el-input v-model="form.applicantName" placeholder="请输入经办人" />
        </el-form-item>
        <el-form-item label="合同编号" prop="contractNumber">
          <el-input v-model="form.contractNumber" placeholder="请输入合同编号" />
        </el-form-item>
        <el-form-item label="合同名称" prop="contractName">
          <el-input v-model="form.contractName" placeholder="请输入合同名称" />
        </el-form-item>
        <el-form-item label="供应商" prop="supplier">
          <el-input v-model="form.supplier" placeholder="请输入供应商" />
        </el-form-item>
        <el-form-item label="验收日期" prop="requiredDate">
          <el-date-picker clearable
            v-model="form.requiredDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择验收日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="本次到货金额合计" prop="deliveryAmount">
          <el-input v-model="form.deliveryAmount" placeholder="请输入本次到货金额合计" />
        </el-form-item>
        <el-form-item label="是否存在分批到货情况" prop="ifBatchDelivery">
          <el-input v-model="form.ifBatchDelivery" placeholder="请输入是否存在分批到货情况" />
        </el-form-item>
        <el-form-item label="是否有专业机构检验验收报告" prop="ifProfessionalOrg">
          <el-input v-model="form.ifProfessionalOrg" placeholder="请输入是否有专业机构检验验收报告" />
        </el-form-item>
        <el-form-item label="是否YS合同" prop="ifYsConstruct">
          <el-input v-model="form.ifYsConstruct" placeholder="请输入是否YS合同" />
        </el-form-item>
        <el-form-item label="Welink合同编号" prop="welinkContractNumber">
          <el-input v-model="form.welinkContractNumber" placeholder="请输入Welink合同编号" />
        </el-form-item>
        <el-form-item label="Welink合同名称" prop="welinkContractName">
          <el-input v-model="form.welinkContractName" placeholder="请输入Welink合同名称" />
        </el-form-item>
        <el-form-item label="申请事由" prop="applicationReason">
          <el-input v-model="form.applicationReason" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="到货日期" prop="arrivalDate">
          <el-date-picker clearable
            v-model="form.arrivalDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择到货日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="物料编码" prop="materialCode">
          <el-input v-model="form.materialCode" placeholder="请输入物料编码" />
        </el-form-item>
        <el-form-item label="物料名称" prop="materialName">
          <el-input v-model="form.materialName" placeholder="请输入物料名称" />
        </el-form-item>
        <el-form-item label="计量单位" prop="measurementUnit">
          <el-input v-model="form.measurementUnit" placeholder="请输入计量单位" />
        </el-form-item>
        <el-form-item label="合同数量" prop="contractQuantity">
          <el-input v-model="form.contractQuantity" placeholder="请输入合同数量" />
        </el-form-item>
        <el-form-item label="本次实际到货数量" prop="actualDeliveryQuantity">
          <el-input v-model="form.actualDeliveryQuantity" placeholder="请输入本次实际到货数量" />
        </el-form-item>
        <el-form-item label="验收结果" prop="acceptanceResult">
          <el-input v-model="form.acceptanceResult" placeholder="请输入验收结果" />
        </el-form-item>
        <el-form-item label="不合格原因" prop="unqualifiedReason">
          <el-input v-model="form.unqualifiedReason" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="前期已到货验收数量" prop="previousDeliveryQuantity">
          <el-input v-model="form.previousDeliveryQuantity" placeholder="请输入前期已到货验收数量" />
        </el-form-item>
        <el-form-item label="前期已到货验收金额" prop="previousDeliveryAmount">
          <el-input v-model="form.previousDeliveryAmount" placeholder="请输入前期已到货验收金额" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看抽屉 -->
    <el-drawer
      title="货物验收详情"
      :visible.sync="drawer"
      size="50%"
      direction="rtl"
    >

      <!-- 自定义标题插槽 -->
  <div slot="title" class="drawer-title">
    <span>采购需求详情</span>
    <el-tag 
      :type="getStatusTagType(formView.approveStatus)"
      size="medium"
      style="margin-left: 10px;"
    >
      <dict-tag 
        :options="dict.type.yy_bip_status" 
        :value="formView.approveStatus"
      />
    </el-tag>
  </div>
      <!-- 第一部分 - 指定字段分组 -->
      <el-card shadow="always" style="margin: 20px;">
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="单据编号">{{ formView.documentNumber }}</el-descriptions-item>
          <el-descriptions-item label="单据日期">{{ parseTime(formView.documentDate, '{y}-{m}-{d}') }}</el-descriptions-item>
             <el-descriptions-item label="采购单位">{{ formView.applicantOrgName }}</el-descriptions-item>
             <el-descriptions-item label="接收部门/研究方向">{{ formView.departmentName }}</el-descriptions-item>
              <el-descriptions-item label="经办人">{{ formView.applicantName }}</el-descriptions-item>
                <el-descriptions-item label="是否YS合同">
                  <dict-tag :options="dict.type.yy_bip_tf" :value="formView.ifYsConstruct"/>
                </el-descriptions-item>
              <el-descriptions-item label="合同编号">{{ formView.contractNumber }}</el-descriptions-item>
              <el-descriptions-item label="合同名称">{{ formView.contractName }}</el-descriptions-item>
              <el-descriptions-item label="供应商">{{ formView.supplier }}</el-descriptions-item>
              <el-descriptions-item label="到货日期">{{ parseTime(formView.arrivalDate, '{y}-{m}-{d}') }}</el-descriptions-item>
              <el-descriptions-item label="本次到货金额合计">{{ formView.deliveryAmount }}</el-descriptions-item>
              <el-descriptions-item label="是否存在分批到货情况">
                <dict-tag :options="dict.type.yy_bip_tf" :value="formView.ifBatchDelivery"/>
              </el-descriptions-item>
           <el-descriptions-item label="是否有专业机构检验验收报告">
            <dict-tag :options="dict.type.yy_bip_tf" :value="formView.ifProfessionalOrg"/>
            </el-descriptions-item>
            <el-descriptions-item label="Welink合同编号">{{ formView.welinkContractNumber }}</el-descriptions-item>
          <el-descriptions-item label="Welink合同名称">{{ formView.welinkContractName }}</el-descriptions-item>
          <el-descriptions-item label="申请事由">{{ formView.applicationReason }}</el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 第二部分 - 其余字段 -->
      <el-card shadow="always" style="margin: 20px;">
        <div class="card-title">验收明细</div> 
        <el-table 
            :data="detailList" 
            border 
            style="width: 100%; margin-top: 10px;"
            :show-header="true"
          >
          <el-table-column label="物料编码" align="center" prop="materialCode" />
          <el-table-column label="物料名称" align="center" prop="materialName" />
          <el-table-column label="品牌/材料/规格" align="center" prop="modelDescription" />
          <el-table-column label="计量单位" align="center" prop="measurementUnit" />
          <el-table-column label="合同数量" align="center" prop="contractQuantity" />
          <el-table-column label="本次实际到货数量" align="center" prop="actualDeliveryQuantity" />
          <el-table-column label="验收结果" align="center" prop="acceptanceResult" />
          <el-table-column label="验收日期" align="center" prop="requiredDate" />
          <el-table-column label="不合格原因" align="center" prop="unqualifiedReason" />
          <!-- <el-descriptions-item label="前期已到货验收数量">{{ formView.previousDeliveryQuantity }}</el-descriptions-item>
          <el-descriptions-item label="前期已到货验收金额">{{ formView.previousDeliveryAmount }}</el-descriptions-item> -->
             </el-table>
      </el-card>
    </el-drawer>
  </div>
</template>

<script>
import { listAcceptanceDetails,listAcceptance, getAcceptance, delAcceptance, addAcceptance, updateAcceptance } from "@/api/sci/acceptance";

export default {
  name: "Acceptance",
  dicts:['yy_bip_status','yy_bip_tf'],
  data() {
    return {
      detailList: [], // 新增明细列表数据
      drawer: false, // 控制抽屉显示
      formView: {},   // 查看表单数据
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备（货物验收数据）表格数据
      acceptanceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        approveStatus: null,
        departmentName: null,
        applicantName: null,
        supplier: null,
        requiredDate: null,
        deliveryAmount: null,
        ifBatchDelivery: null,
        ifYsConstruct: null,
        arrivalDate: null,
        materialName: null,
        modelDescription: null,
        contractQuantity: null,
        actualDeliveryQuantity: null,
        acceptanceResult: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        documentNumber: [
          { required: true, message: "单据编号不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
     /** 查看按钮操作 */
    handleView(row) {
      const id = row.id || this.ids;
      const code = row.documentNumber;

      // 获取明细数据
        listAcceptanceDetails(row.documentNumber).then(detailResponse => {
          this.formView = detailResponse.data[0];
          this.detailList = detailResponse.data;
          this.drawer = true;
        }).catch(() => {
          this.detailList = [];
          this.drawer = true;
      //  });
      });
    },
    
    // 时间格式化方法
    parseTime(time, format = '{y}-{m}-{d}') {
      if (!time) return '';
      let date = new Date(time);
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds()
      };
      return format.replace(/{([ymdhisa])+}/g, (result, key) => {
        const value = formatObj[key];
        return value.toString().padStart(2, '0');
      });
    },
    /** 查询设备（货物验收数据）列表 */
    getList() {
      this.loading = true;
      listAcceptance(this.queryParams).then(response => {
        this.acceptanceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        approveStatus: null,
        documentNumber: null,
        documentDate: null,
        applicantOrgName: null,
        departmentName: null,
        applicantName: null,
        contractNumber: null,
        contractName: null,
        supplier: null,
        requiredDate: null,
        deliveryAmount: null,
        ifBatchDelivery: null,
        ifProfessionalOrg: null,
        ifYsConstruct: null,
        welinkContractNumber: null,
        welinkContractName: null,
        applicationReason: null,
        arrivalDate: null,
        materialCode: null,
        materialName: null,
        modelDescription: null,
        measurementUnit: null,
        contractQuantity: null,
        actualDeliveryQuantity: null,
        acceptanceResult: null,
        unqualifiedReason: null,
        previousDeliveryQuantity: null,
        previousDeliveryAmount: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备（货物验收数据）";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAcceptance(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备（货物验收数据）";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAcceptance(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAcceptance(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除设备（货物验收数据）编号为"' + ids + '"的数据项？').then(function() {
        return delAcceptance(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('sci/acceptance/export', {
        ...this.queryParams
      }, `acceptance_${new Date().getTime()}.xlsx`)
    },
      getStatusTagType(status) {
    switch(status) {
      case 0: return 'info';    // 未提交
      case 3: return 'warning'; // 审批中
      case 1: return 'success'; // 审批通过
      default: return 'info';
    }
  },
  }
};
</script>

<style scoped>
/* 添加抽屉内容的样式 */
.el-drawer__body {
  padding: 0;
  overflow-y: auto;
}

.el-card {
  margin-bottom: 15px;
}

.el-descriptions__title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
}
.card-title{
   font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
}
</style>
